package com.example.zyfypt516wh.activities;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zyfypt516wh.R;
import com.example.zyfypt516wh.common.Common;
import com.example.zyfypt516wh.service.RetrofitService;
import com.github.barteksc.pdfviewer.PDFView;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
//pdf
public class ViewTwareActivity extends AppCompatActivity {
    private PDFView pdfView;
    private TextView tvtwarename;
    private String name = "";//pdf 名字
    private String attach = "";//pdf 相对地址
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_tware);
        pdfView = findViewById(R.id.pdfView);
        tvtwarename=findViewById(R.id.tvtwarename); attach = getIntent().getStringExtra("pdfattach"); name = getIntent().getStringExtra("name");
        System.out.println("----课件 pdf 相对地址：" + attach);
        System.out.println("----课件 pdf 相名字：" + name);
        if(attach!=null) {
            loadPdf();
        }else {
            Toast.makeText(this, "未找到课件文件", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    private void loadPdf(){
//设置 Retrofit 访问网络的超时时间
        OkHttpClient client = new OkHttpClient.Builder(). connectTimeout(600, TimeUnit.SECONDS). readTimeout(600, TimeUnit.SECONDS). writeTimeout(600, TimeUnit.SECONDS).build();
        Retrofit retrofit =new Retrofit.Builder()
                .baseUrl(Common.IMAGEURL)
                .client(client)
                .build();
        RetrofitService service = retrofit.create(RetrofitService.class);
        Call<ResponseBody> call = service.getPdf(attach); call.enqueue(new Callback<ResponseBody>() {
            @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()){
                    try {
                        byte[] data = response.body().bytes();
                        pdfView.fromBytes(data).swipeHorizontal(true).load();//加载 PDF
                        tvtwarename.setText(name);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            @Override public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("--pdf 查看--"+t.toString());
                Toast.makeText(ViewTwareActivity.this, "pdf 查看--"+t.toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}